package com.xuyh.mqtt.mqtt;


import com.alibaba.fastjson.JSON;
import com.xuyh.mqtt.realtime.dal.DeviceDataDal;
import com.xuyh.mqtt.realtime.dto.DeviceDataDto;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消费监听类
 */
@Slf4j
@Component
public class PushCallback implements MqttCallback {

    @Autowired
    private DeviceDataDal deviceDataDal;

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        log.info("连接断开，可以做重连");
//        if (client == null || !client.isConnected()) {
//            mqttConfig.getMqttPushClient();
//        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {
        // subscribe后得到的消息会执行到这里面
        log.info("接收消息主题 : " + topic);
        log.info("接收消息Qos : " + mqttMessage.getQos());
        String result = new String(mqttMessage.getPayload());
        log.info("接收消息内容 : " + result);
        if (!"1234567890999".equals(result)) {
            DeviceDataDto deviceDataDto = JSON.parseObject(result, DeviceDataDto.class);
            if (deviceDataDal != null && deviceDataDto != null) {
                deviceDataDal.save(deviceDataDto);
            }
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }
}
